<?php
/*
 * Platwo Exception
 * You can throw error exception and render to JSON
 * 
 * try {
 * 		if(!isset($_GET['var'])) {
 * 			throw new PlatwoException(20);
 * 		}
 * } catch (PlatwoException $e) {
 * 		echo $e->toJSON();
 * 		Yii::app()->end();
 * }
 * 
 */

Class PlatwoException extends Exception
{
	protected $code = 0;
	protected $message = 'none.';
	protected $logFile = 'protected/pla2Logs/logs.txt';
	protected $time;
	
	public function __construct($code, $message = null)
	{
		$this->time = date("Y:m:d H:i:s");
		$this->code = $code;
		if($message != null) {
			$this->message = $message;
		}
		else {
			$this->message = ErrorMessage::getMessage($this->code);
		}
	}
	
	public function toJSON()
	{
		$data = array('error'=>array('code'=> $this->code, 'message'=> $this->message, 'type'=> __CLASS__));
		return CJSON::encode($data);
	}
	
	public function toArray()
	{
		return array('error'=>array('code'=> $this->code, 'message'=> $this->message, 'type'=> __CLASS__));
	}
	
	public function saveLog()
	{
		$message = $this->time.", Error Code: ".$this->getCode().", ".$this->getMessage()."\n";
		if(!file_exists($this->logFile)) {
			mkdir($this->logFile, 0777);
		}
		file_put_contents($this->logFile, $message, FILE_APPEND);
	}
}
